package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.Com.User;
import com.itheima.common.vo.LoginVo;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Boolean sendMsg(User user) {

        if (user == null) {
            throw new RuntimeException("数据为空");
        }

        String phone = user.getPhone();
        User user1 = userMapper.findbyphome(phone);
        if (user1 == null) {
//            说破该手机号未注
//                    执行注册
            user.setId(IdUtil.getSnowflakeNextIdStr());
            userMapper.sendMsg(user);

        }
        //生成随机数
        int number = new Random().nextInt(100000) + 100000;
        log.info("{}", number);
        //存到redis里面
        redisTemplate.opsForValue().set("code" + user.getPhone(), number + "", 2L, TimeUnit.HOURS);

        return true;
    }

    @Override
    public LoginVo login(User user) {

        User findbyphome = userMapper.findbyphome(user.getPhone());
        log.info("{}",findbyphome);

        String key = "5201314";
        Map<String, Object> map = new HashMap<>();
        map.put("phone", findbyphome.getPhone());
        String token = JWTUtil.createToken(map, key.getBytes());
        userMapper.login(findbyphome);

        redisTemplate.opsForValue().set("token" + token, JSON.toJSONString(findbyphome), 3, TimeUnit.HOURS);
        LoginVo loginVo = new LoginVo();
        BeanUtils.copyProperties(findbyphome, loginVo);
        loginVo.setToken(token);
        loginVo.setId(IdUtil.getSnowflakeNextIdStr());

        return loginVo;
    }

    @Override
    public void loginput(String token) {
        LoginVo byToken = userMapper.getByToken(token);
        userMapper.updateById(byToken.getId());
    }


}
